package cdn_url

import (
	"context"
	"crypto/md5"
	"encoding/json"
	"fmt"
	"github.com/gogf/gf/v2/frame/g"
	"time"
	"video-api/utility/redis_client"
)

// https://www.alibabacloud.com/help/zh/cdn/user-guide/type-b-signing
var (
	KEY1        = "skTvw92YWBpZZekjFj"
	KEY2        = "KbSj8AbBHYFrYUE8aT"
	CDN_URL_KEY = "CDN_URL:"
)

// cdn的信息
type CDNURLInfo struct {
	Url       string `json:"url"`
	Timestamp int64  `json:"timestamp"`
}

// CdnUrl generates a CDN URL for the given URI using the specified key and default timeout.
// It is an exported function intended for use by other packages to obtain CDN URLs.
// The function internally calls another function with the same name but different parameters.
// Example usage: CdnUrl("/testing/video.mp4")
func CdnUrl(prefix, uri string) (*CDNURLInfo, error) {
	ctx := context.TODO()
	// 查看缓存是否有这个url的值，有则直接取，不用获取新的cdn链接。减少流量计费
	url, _ := redis_client.RedisClient.Get(ctx, CDN_URL_KEY+uri).Result()
	if url == "" {
		return cdnUrl(ctx, prefix, uri, KEY1, 0)
	}
	info := new(CDNURLInfo)
	err := json.Unmarshal([]byte(url), info)
	if err != nil {
		return cdnUrl(ctx, prefix, uri, KEY1, 0)
	}
	return info, nil
}

func cdnUrl(ctx context.Context, prefix, uri, key string, timeoutMore time.Duration) (*CDNURLInfo, error) {
	// todo 测试数据
	timeoutMore = 2 * time.Minute

	info := new(CDNURLInfo)
	//loc, err := time.LoadLocation("Asia/Shanghai")
	//if err != nil {
	//	log.Println("加载时区失败:", err)
	//	return info, err
	//}
	// cdn默认30分钟时效
	//eastEightTime := time.Now().In(loc).Add(timeoutMore)
	eastEightTime := time.Now().Add(timeoutMore)
	formattedTime := eastEightTime.Format("200601021504")
	hash := md5.Sum([]byte(key + formattedTime + uri))
	newUrl := fmt.Sprintf("%s/%s/%x%s", prefix, formattedTime, hash[:], uri)
	info.Url = newUrl
	if timeoutMore > 0 {
		info.Timestamp = eastEightTime.Unix()
	} else {
		info.Timestamp = time.Now().Add(30 * time.Minute).Unix()
	}
	newUrlInfo, _ := json.Marshal(info)
	// 将url存入缓存10分钟，减少频繁的cdn生成链接带来的计费成本
	err := redis_client.RedisClient.Set(ctx, CDN_URL_KEY+uri, string(newUrlInfo), 1*time.Minute).Err()
	if err != nil {
		g.Log().Warning(ctx, "cdnUrl-RedisClient-Set err：", err, g.Map{"url": newUrl})
	}

	return info, nil
}
